<?php

/*
 * Source
 * http://snipplr.com/view/2531/
 */

include '../DBAccess/DBAccess.php';
$latTest = 46.694603;
$lngTest = 9.634391;

//getCloserWSTemp(46.694603, 9.634391, 438);
echo getCloserWSSun($latTest, $lngTest, 438);
echo'----------------';
echo'<br/>';
//getAllDistances($latTest, $lngTest);

//echo(getDistance($latTest, $lngTest, 46.77862, 9.676552));
//echo'....';
//echo(getDistance(46.694603, 9.634391, 47.695303, 8.631591));

function getDistance($lat1, $lng1, $lat2, $lng2) {
    $miles = false;
    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lng1 *= $pi80;
    $lat2 *= $pi80;
    $lng2 *= $pi80;

    $r = 6372.797; // mean radius of Earth in km
    $dlat = $lat2 - $lat1;
    $dlng = $lng2 - $lng1;
    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $km = $r * $c;

    return ($miles ? ($km * 0.621371192) : $km);
}

// OK
function getCloserWSTemp($lat, $lng, $houseElevation) {
    $id = null;
    $distance = null;
    $distanceTemp = null;
    $elevation = null;
    $closerStation = null;
    $elevationEquals = array(); // We need to store all the stations with an equal elevation
    $diff = null;
    $diffTemp = null;

    try {
        $db = new DBAccess('153.109.141.81:3306', 'savenrj', 'root', '');
        $relsult;
        $result = $db->getWeatherStation();


        foreach ($result as $value) {
            $elevation = $value['Altitude'];
            if ($elevation == $houseElevation) {
                array_push($elevationEquals, $value); // We need to acces to lat and lng later in the code
            } else {
                if (count($elevationEquals) > 0) { // We calculate the difference only if we do not have an equal elevation
                    // Calculate the difference between $elevation and current elevation
                    if ($value['Altitude'] > $houseElevation) {
                        $diffTemp = $value['Altitude'] - $houseElevation;
                    } else {
                        $diffTemp = $houseElevation - $value['Altitude'];
                    }
                    // Update $elevation if we found a closer value
                    if ($diff != null) {
                        if ($diffTemp < $diff) {
                            $diff = $diffTemp;
                            $closerStation = $value; // We need to acces to lat and lng later in the code
                        }
                    } else {
                        $diff = $diffTemp;
                        $closerStation = $value; // We need to acces to lat and lng later in the code
                    }
                }
            }
        }

        if (count($elevationEquals) > 0) {
            if (count($elevationEquals) == 1) { // There is only one station
                $id = $elevationEquals[0]['IdNorm_Weather'];
            } else { // Multiple station found
                foreach ($elevationEquals as $station) {
                    $distanceTemp = getDistance($lat, $lng, $station['Latitude'], $station['Longitude']);
                    if ($distance == null || $distance > $distanceTemp) {
                        $distance = $distanceTemp;
                        $closerStation = $station;
                    }
                }
                $id = $closerStation['IdNorm_Weather'];
            }
        } else { // There is only one station
            $id = $closerStation['IdNorm_Weather'];
        }
        echo $id;
    } catch (MySQLExeption $e) {
        echo $e->RetourneErreur();
    }
    return $id;
}

function getCloserWSSun($lat, $lng, $houseElevation) {
    $id = null;
    $distance = null;
    $distanceTemp = null;
    $elevation = null;
    $elevationTemp = null;
    $closerStation = null;
    $distancesEquals = array(); // We need to store all the stations with an equal elevation
    $diff = null;
    $diffTemp = null;

    try {
        $db = new DBAccess('153.109.141.81:3306', 'savenrj', 'root', '');
        $relsult;
        $result = $db->getWeatherStation();

        foreach ($result as $station) {
            if ($distance == null) {
                $distance = getDistance($lat, $lng, $station['Latitude'], $station['Longitude']);
            } else {
                $distanceTemp = getDistance($lat, $lng, $station['Latitude'], $station['Longitude']);
                if ($distance == $distanceTemp) {
                    array_push($distancesEquals, $station); // We need to acces to  elevation later in the code
                    $distance = $distanceTemp; // Store the actual closer station
                } else {
                    if ($distance > $distanceTemp) {
                        $distance = $distanceTemp;
                        $closerStation = $station;
                    }
                }
            }
        }


        // The case that multiple stations have the same distance to the hous AND the same elevation as the house is impossible...

        if (count($distancesEquals) > 0) {
            if (count($distancesEquals) == 1) { // There is only one station
                $id = $distancesEquals[0]['IdNorm_Weather'];
            } else { // Multiple station found
                foreach ($distancesEquals as $station) {
                    if ($elevation == null) {
                        $elevation = $station['Altitude'];
                    }
                    // Calculate the difference between $elevation and current elevation
                    if ($station['Altitude'] > $houseElevation) {
                        $diffTemp = $station['Altitude'] - $houseElevation;
                    } else {
                        $diffTemp = $houseElevation - $station['Altitude'];
                    }
                    // Update $elevation if we found a closer value
                    if ($diffTemp < $diff) {
                        $diff = $diffTemp;
                        $closerStation = $station; // We need to acces to lat and lng later in the code
                    }
                }
                $id = $closerStation['IdNorm_Weather'];
            }
        } else { // There is only one station
            $id = $closerStation['IdNorm_Weather'];
        }
    } catch (MySQLExeption $e) {
        echo $e->RetourneErreur();
    }
    return $id;
}

function getWeatherStationInJSArray() {
    try {
        $db = new DBAccess('153.109.141.81:3306', 'savenrj', 'root', '');
        $result;
        $result = $db->getWeatherStation();
        $jsArray = 'var weatherStation=new Array();';
        $flag = 0;

        foreach ($result as $value) {
            $jsArray = $jsArray . 'weatherStation[' . $flag . ']="' . $value[1] . '";';
            $flag++;
        }
    } catch (MySQLExeption $e) {
        echo $e->RetourneErreur();
    }
    return $jsArray;
}

function getAllDistances($lat, $lng) {
    try {
        $db = new DBAccess('153.109.141.81:3306', 'savenrj', 'root', '');
        $relsult;
        $result = $db->getWeatherStation();

        foreach ($result as $station) {
            echo getDistance($lat, $lng, $station['Latitude'], $station['Longitude']);
            echo'     ' . $station['City'];
            echo'<br/>';
        }
    } catch (MySQLExeption $e) {
        echo $e->RetourneErreur();
    }
}

?>